import { User } from './../../interfaces/request.interface';
import { map } from 'rxjs/operators';
import { SysStaffRoleEntity } from './../../entity/sys-staff-role.entity';
import { AuthService } from './../auth/auth.service';
import { LoginDto } from './../user/dto/login.dto';
import { CommonRepService } from './../../common/services/commonRep.service';
import { Injectable, BadRequestException, UseGuards, forwardRef, Inject } from '@nestjs/common';
import { SysStaffEntity } from 'src/entity/sys-staff.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class StaffService extends CommonRepService<SysStaffEntity>{
    constructor(
        @InjectRepository(SysStaffEntity) private readonly sysStaffRep: Repository<SysStaffEntity>,
        @InjectRepository(SysStaffEntity) private readonly sysStaffRoleRep: Repository<SysStaffRoleEntity>,
        @Inject(forwardRef(() => AuthService))
        private readonly authServ: AuthService
    ) {
        super(sysStaffRep);
    }

    async login(dto: LoginDto): Promise<any> {
        const one = await this.sysStaffRep.findOne({ username: dto.username });
        if (!one) {
            throw new BadRequestException('用户不存在');
        }

        if (dto.password !== one.password) {
            throw new BadRequestException('用户或密码错误！')
        }

        const roles = await this.queryRolesById(one.id);
        const payload: User = { id: one.id, username: one.username, type: 'admin' }
        
        return {
            accessToken: this.authServ.sign(payload),
            roles,
            id: one.id,
            username: one.username,
        };
    }

    /**
     * 查询员工角色
     * @param id 
     */
    async queryRolesById(id: string): Promise<any> {
        const list = await this.sysStaffRoleRep.query(`
            SELECT r.roleCode
            FROM sys_staff_role sr
            LEFT JOIN sys_role r on r.id = sr.roleId
            WHERE sr.staffId = ${id}
        `);
        return list.map(item => item.roleCode);
    }

}
